<template>
  <div class="loginMobile">
    <div class="formK">
      <div class="form">
        <div class="title">
          <img :src="img.logo" alt="" />
          <span>{{ $store.state.projectName }}</span>
        </div>
        <div class="title" style="margin: 10px auto 160px; width: 100%">
          <p style="width: 100%; text-align: right">- 管理平台</p>
        </div>
        <el-form
          :rules="rules"
          :model="form"
          class="ruleForm"
          style="width: 100%"
          ref="ruleForm"
        >
          <el-form-item prop="admin_account">
            <el-input
              v-model="form.admin_account"
              placeholder="请输入登录账号"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item prop="admin_password">
            <el-input
              v-model="form.admin_password"
              placeholder="请输入登录密码"
              size="large"
              show-password
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="optionsDom">
          <span @click="openAddDialog">注册</span>
          <!-- <span>忘记密码</span> -->
        </div>
        <el-button type="primary" class="sumbit" size="large" @click="sumbit()"
          >登录</el-button
        >
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      title=""
      fullscreen
      :before-close="handleCloseAddDialog"
    >
      <el-form
        style="margin-top: 30px"
        :model="formc"
        :rules="rulesc"
        ref="formdRef"
        label-width="150px"
        label-position="top"
        class="demo-form"
      >
        <el-form-item label="手机号" prop="admin_account">
          <el-input
            v-model="formc.admin_account"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="admin_username">
          <el-input
            v-model="formc.admin_username"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="admin_gender">
          <el-radio-group v-model="formc.admin_gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <!-- <el-radio :label="0">未知</el-radio> -->
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="dialogType != 'edit'"
          label="密码"
          prop="admin_password"
        >
          <el-input
            v-model="formc.admin_password"
            type="password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="dialogType != 'edit'"
          label="确认密码"
          prop="admin_confirm_password"
        >
          <el-input
            v-model="formc.admin_confirm_password"
            type="password"
            placeholder="请再次输入密码"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="职位" prop="role_id">
          <el-select
            v-model="formc.role_id"
            @change="changeRole"
            placeholder="请选择角色"
          >
            <el-option label="英特平台管理员" :value="2"></el-option>
            <el-option label="英特平台人事" :value="3"></el-option>
            <el-option label="合作单位管理员" :value="4"></el-option>
            <el-option label="合作单位人事" :value="5"></el-option>
            <el-option label="合作单位项目领导" :value="6"></el-option>
            <el-option label="合作单位项目人事" :value="7"></el-option>
            <el-option label="合作单位部门领导" :value="8"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="compontMShow" label="选择范围">
          <multipleCompany
            @change="changeMultipleCompany"
            :level="compontMLevel"
            ref="multipleCompany"
            isPhone
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" class="sumbit" size="large" @click="submitForm">
        注册
      </el-button>

    </el-dialog>
  </div>
</template>

<script>
import img from "@/assets/img/import.js";
import multipleCompany from "@/components/multipleCompany.vue";
export default {
  components: { multipleCompany },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度不能少于6位"));
      } else {
        callback();
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value != this.formc.admin_password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        if (this.form.admin_confirm_password !== "") {
          this.$refs.formdRef.validateField("admin_confirm_password");
        }
        callback();
      }
    };

    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      img,
      dialogVisible: false,
      dialogType: "",
      formc: {
        admin_account: "",
        admin_username: "",
        admin_gender: 0,
        admin_password: "",
        admin_status: 1,
        admin_confirm_password: "",
        role_id: "",
        adminScopeArr: [],
      },

      compontMShow: false,
      compontMLevel: 1,
      rulesc: {
        admin_account: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        admin_username: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        admin_gender: [
          { required: true, message: "请选择性别", trigger: "change" },
        ],
        admin_password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        admin_confirm_password: [
          {
            required: true,
            validator: validateConfirmPassword,
            trigger: "blur",
          },
        ],
        role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      form: {
        admin_account: "",
        admin_password: "",
      },
      rules: {
        admin_account: [
          {
            required: true,
            message: "请输入登录账号",
            trigger: "change",
          },
        ],
        admin_password: [
          {
            required: true,
            message: "请输入登录密码",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    sumbit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$request.common.login(this.form).then((res) => {
            if (res && res.data.code == 200) {
              this.$store.commit("setToken", res.data.content.token);
              this.$request.common.getAdminUserInfoByToken().then((e) => {
                if (res && res.data.code == 200) {
                  this.$message.success("登录成功");
                  this.$store.commit("setUserInfo", e.data.content.data);
                  this.$store.commit("$navTo", "/administrators");
                }
              });
            } else {
              // this.$message.error(res.data.message);
            }
          });
        } else {
          return false;
        }
      });
    },

    changeRole(val) {
      if (this.$refs["multipleCompany"]) {
        this.$refs["multipleCompany"].clearDate(val);
      }
      //英特平台管理员
      if (val == 2 || val == 1) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 1;
        this.compontMShow = false;
      }
      //英特平台人事
      if (val == 3) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 1;
        this.compontMShow = true;
      }
      //合作单位管理员
      if (val == 4) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 0;
        this.compontMShow = true;
      }
      //合作单位人事
      if (val == 5) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 0;
        this.compontMShow = true;
      }
      //合作单位项目领导
      if (val == 6) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 2;
        this.compontMShow = true;
      }
      //合作单位项目人事
      if (val == 7) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 2;
        this.compontMShow = true;
      }
      //合作单位项目人事
      if (val == 8) {
        this.form.adminScopeArr = [];
        this.compontMLevel = 3;
        this.compontMShow = true;
      }
    },

    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
      if (option == "edit") {
        const initObj = {
          company_id: "",
          community_id: "",
          department_id: "",
        };
        //英特平台人事
        if (this.form.role_id == 3) {
          if (this.form.admin_scope_data.length == 0) {
            initObj.company_id = ["-1"];
          } else {
            let arr = [];
            for (
              let index = 0;
              index < this.form.admin_scope_data.length;
              index++
            ) {
              const element = this.form.admin_scope_data[index];
              arr.push(element.company_id);
            }
            initObj.company_id = [...new Set(arr)];
          }
        }
        //合作单位管理员
        if (this.form.role_id == 4) {
          initObj.company_id = this.form.admin_scope_data[0].company_id;
        }
        //合作单位人事
        if (this.form.role_id == 5) {
          initObj.company_id = this.form.admin_scope_data[0].company_id;
        }
        //合作单位项目领导
        if (this.form.role_id == 6) {
          let arr = [];
          let isAll = false;
          for (
            let index = 0;
            index < this.form.admin_scope_data.length;
            index++
          ) {
            const element = this.form.admin_scope_data[index];
            if (element.community_id == 0 || isAll) {
              arr = ["-1"];
              isAll = true;
              break;
            }
            arr.push(element.community_id);
          }
          initObj.company_id = this.form.admin_scope_data[0].company_id;
          initObj.community_id = [...new Set(arr)];
        }
        //合作单位项目人事
        if (this.form.role_id == 7) {
          let arr = [];
          let isAll = false;
          for (
            let index = 0;
            index < this.form.admin_scope_data.length;
            index++
          ) {
            const element = this.form.admin_scope_data[index];
            if (element.community_id == 0 || isAll) {
              arr = ["-1"];
              isAll = true;
              break;
            }
            arr.push(element.community_id);
          }
          initObj.company_id = this.form.admin_scope_data[0].company_id;
          initObj.community_id = [...new Set(arr)];
        }
        //合作单位项目人事
        if (this.form.role_id == 8) {
          let arr = [];
          let isAll = false;
          for (
            let index = 0;
            index < this.form.admin_scope_data.length;
            index++
          ) {
            const element = this.form.admin_scope_data[index];
            if (element.department_id == 0 || isAll) {
              arr = ["-1"];
              isAll = true;
              break;
            }
            arr.push(element.department_id);
          }
          initObj.company_id = this.form.admin_scope_data[0].company_id;
          initObj.community_id = this.form.admin_scope_data[0].community_id;
          initObj.department_id = [...new Set(arr)];
        }
        setTimeout(() => {
          this.changeRole(this.form.role_id);
          this.$refs["multipleCompany"].setobjInfo(initObj);
        }, 1000);
      }
    },
    handleCloseAddDialog() {
      this.$refs["multipleCompany"].clearDate(0);
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        admin_account: "",
        admin_username: "",
        admin_gender: 0,
        admin_password: "",
        admin_status: 1,
        admin_confirm_password: "",
        role_id: "",
        adminScopeArr: [],
      };
      this.resetForm();
    },
    submitForm() {
      if (
        this.form.role_id != 2 &&
        this.form.role_id != 3 &&
        this.form.adminScopeArr.length == 0
      ) {
        this.$message.error("请检查角色, 还有公司范围");
      }
      this.$refs.formdRef.validate((valid) => {
        if (valid) {
          // 表单验证通过，提交逻辑
          // console.log("表单提交:", this.form);
          if (this.dialogType == "edit") {
            api.AccountList.UpdateApi({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          } else {
            api.AccountList.createApi({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          }

          // 这里可以添加API调用等提交逻辑
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.formdRef.resetFields();
    },

    changeMultipleCompany(val) {
      // console.log("=====",val.length)
      this.form.adminScopeArr = val;
    },
  },
};
</script>

<style lang="scss">
.optionsDom {
  width: 100%;
  display: flex;
  justify-content: space-between;
  span {
    color: var(--el-color-primary);
    font-size: 14px;
  }
}

.sumbit {
  width: 80%;
  margin: 20px 10% 0;
  height: 40px;
  border-radius: 40px;
  overflow: hidden;
}
.loginMobile {
  width: 100%;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;

  .formK {
    flex: 1;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;

    .form {
      width: 400px;
      height: 50%;
      min-height: 300px;
      box-shadow: 0 0 20px 0 rgba(156, 156, 156, 0.2);
      background: rgba(255, 255, 255, 0.8);
      border-radius: 20px;
      padding: 40px 30px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      z-index: 4;
      .el-input {
        opacity: 0.8;
        width: 100%;
        height: 56px;
        overflow: hidden;
      }
      .el-input--large .el-input__wrapper {
        padding: 1px 15px;
        border-radius: 16px;
      }
      .title {
        display: flex;
        flex-direction: row;
        align-items: flex-end;
        margin: 40px auto 10px;
        img {
          width: 60px;
          height: 60px;
          margin-right: 20px;
          border-radius: 10px;
        }

        span {
          font-size: 30px;
          font-weight: bold;
          color: var(--el-color-primary);
        }
        text,
        p {
          padding: 4px 0;
          font-size: 20px;
          font-weight: bold;
          margin-left: 8px;
          color: var(--el-color-primary);
        }
      }

      .sumbit {
        width: 100%;
        margin-top: 30px;
        height: 48px;
        border-radius: 48px;
        overflow: hidden;
      }
    }
  }
}
</style>
